<?php
/**
 * Created by PhpStorm.
 * User: Larry
 * Date: 16/4/5
 * Time: 19:15
 */

namespace App\Services\Wechat;


use App\Support\Wechat\Payment;
use App\Support\Wechat\Payment\Order;
use App\Support\Wechat\Payment\Business;
use App\Support\Wechat\Payment\UnifiedOrder;


class WechatMch
{

    public function __construct(
        \App\Models\WechatMch $wechatMch
    )
    {
        $this->wechatMch = $wechatMch->getWechatMch();
    }

    /**
     * @param $openid
     * @param $sn 订单号
     * @param $money 金额
     * @param $type 1,支付 2,充值
     */
    public function weixinpay($openid, $sn, $money, $type = 1)
    {
        if ($money < 1)
        {
            $money = 1;
        }
        /**
         * 第 1 步：定义商户
         */
        $business = new Business(
            $this->wechatMch['app_id'],
            $this->wechatMch['app_secret'],
            $this->wechatMch['mch_id'],
            $this->wechatMch['mch_key']
        );

        /**
         * 第 2 步：定义订单
         */
        if($type == 1)
        {
            $url = 'http://yiyuanshibao.com/w/pay/notify';
        }
        else
        {
            $url = 'http://yiyuanshibao.com/w/member/notify';
        }
        $out_trade_no = md5(uniqid().microtime());
        $order = new Order();
        $order->body = '订单编号:W'.$sn;
        $order->out_trade_no = $out_trade_no;
        $order->total_fee = $money*100;    // 单位为 “分”, 字符串类型
        $order->openid = $openid;
        $order->notify_url = $url;

        /**
         * 第 3 步：统一下单
         */
        $unifiedOrder = new UnifiedOrder($business, $order);

        /**
         * 第 4 步：生成支付配置文件
         */
        $payment = new Payment($unifiedOrder);
        $sn = $out_trade_no;
        return view('wechat.pay.wxpay', compact('order', 'payment', 'sn', 'type'));
    }

}